package zm.irc.threads;
import java.io.IOException;
import org.apache.log4j.Logger;
import zm.irc.client.IrcClient;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.message.send.IrcSendMessage;
import zm.irc.msgqueue.LocalMemoryMsgQueue;
import zm.irc.util.CommonUtil;


@Service
public class MsgSendThread extends IrcThread{
    private static Logger log = Logger.getLogger(MsgSendThread.class);

    @AutoWired
    private LocalMemoryMsgQueue localMemoryMsgQueue ;


    @AutoWired
    private IrcClient client;

    private  IrcSendMessage msg;
 

    @AutoWired
    private CommonUtil commonUtil;
    
    @Override
    public void beforeLoop(){
        log.info("Message send Thread Start.");
    }


    @Override
    public void before(){
        msg = localMemoryMsgQueue.getMsgFromSendQueue();
    }

    @Override
    public void doRun() {
        try {
            commonUtil.slowDown(1000);
            if (msg == null) {
                return;
            }
            this.sendMessageDirect(msg);
        } catch (Exception e) {
            log.error("error", e);
        }

    }


    /**
     * <pre>
     * Please do not send message by this method!
     * Only for {@link MsgSendThread}.
     * </pre>
     * @param msg
     * @throws IOException
     */
    public synchronized void sendMessageDirect(IrcSendMessage msg) throws Exception {
        this.client.sendMessageDirect(msg.getMessage());
    }
}
